<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/12/27
 * Time: 11:49
 */

namespace app\sales\controller;


use app\api\model\user\Users;
use app\common\model\ApiResponse;
use app\common\model\BuyBill;
use app\sales\lib\AbstractSalesController;
use think\Db;
use think\Log;

class Buy extends AbstractSalesController
{

    public function order() {
        $form = $this->getAndCheckForm([
            ['userid', 'require|integer',],
            ['item_type', 'require|integer',],
            ['item_id', 'require|integer',],
            ['pay_method', 'require|integer',],
        ]);
        $itemType = intval($form['item_type']);
        $itemId = intval($form['item_id']);

        // 检查用户手机
        $user = Users::get($form['userid']);
        if (empty($user)) {
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'用户不存在');
        }

        // 检查已购买
        if (BuyBill::checkBought($itemType, $user->id, $itemId)) {
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED, '您已经购买了');
        }

        // 检查商品
        $item = BuyBill::getBuyInfo($itemType, $user->id, $itemId);
        if (empty($item)) {
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'购买的商品不存在');
        }

        $orderNo = BuyBill::generateOrderNo($user->id);
        $data = [
            'order_no' => $orderNo,
            'pay_amount' => $item['price'],
        ];
        try{

            Db::startTrans();

            // 创建内部购买订单
            $bill = BuyBill::create([
                'bill_no' => $orderNo,
                'bill_user' => $user->id,
                'bill_item_type' => $form['item_type'],
                'bill_item_id' => $form['item_id'],
                'bill_source' => 2, // vip在微信端
                'bill_pay_amount' => $item['price'],
                'bill_pay_method' => $form['pay_method'],
                'bill_payable_amount' => $item['price_orig'],
                'bill_item_title' => $item['title'],
                'bill_item_detail' => $item['detail'],
                'bill_createtime' => time(),
                'bill_trade_way' => BuyBill::TRADE_WAY_OFFLINE,
                'bill_type' => BuyBill::BILL_TYPE_CASH_PAY,
                'credit_cost' => 0,
            ]);

            Db::commit();

            $data['bill_id'] = $bill->bill_id;
            $data['create_time'] = $bill->bill_createtime;
            $data['have_paid'] = false;
            return ApiResponse::success($data);

        } catch (\Exception $ex){

            Db::rollback();
            Log::error('销售下单失败：'.$ex->getCode().' => '.$ex->getMessage());
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED, '创建订单失败');
        }
    }


}